/**!
other function
- csdn crawler
- other
*/
extern crate reqwest;
extern crate visdom;
use ansi_term::Colour;
use serde_json;
use std::error::Error;
use url::Url;
use visdom::Vis;

pub fn get_csdn(urls: &str) -> Result<(), Box<dyn std::error::Error>> {
    let hurl = Url::parse(urls)?;
    let host = hurl.host_str().unwrap_or_else(|| {
        println!("can't get hostname");
        "host is none"
    });
    if "blog.csdn.net".eq(host) {
        let resp = reqwest::blocking::get(urls)?.text()?;
        //#mainBox > main > div.blog-content-box > article
        let cont = Vis::load(resp.as_str())
            .unwrap()
            .find("#mainBox > main > div.blog-content-box > article")
            .text()
            .trim()
            .to_string();
        println!("{}", cont);
        Ok(())
    } else {
        println!(
            "domain is not blog.csdn.net \n {}",
            Colour::Red.paint("you can code it!")
        );
        Err(Box::<dyn Error>::from("domain is not blog.csdn.net"))
    }
}

pub fn color_print() {
    println!(
        "This is {} in color, {} in color and {} in color",
        Colour::Red.paint("red"),
        Colour::Blue.paint("blue"),
        Colour::Green.paint("green")
    );
}

pub fn search_request(
    qry: &str,
    author: &bool,
    fname: &bool,
    qtype: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let urls = format!(
        "http://localhost:9999/api/s?q={}&qtype={}&author={}&fname={}",
        qry, qtype, *author, *fname
    );
    let resp = reqwest::blocking::get(urls)?.text()?;
    /*
    let resp = reqwest::get(urls).await?
    .text().await?;
    */
    let v: web::SearchResult = serde_json::from_str(&resp)?;
    println!(
        "search: {}, counts = {}\n------------------------------",
        v.qry,
        v.results.len()
    );

    for (i, x) in v.results.iter().enumerate() {
        println!(
            "{}. [author]: {}, [filename]: {}\n{} ...\n",
            i, x.author, x.fname, x.content
        );
    }
    Ok(())
}
